

import type { UseFetchOptions } from '#app'
import type { NitroFetchRequest } from 'nitropack'

interface ApiResponse<T> {
    code: number
    data: T
    message?: string
}

export const useApi = () => {
    const config = useRuntimeConfig()
    const baseURL = config.public.baseUrl as string

    // 通用请求封装（严格类型版）
    const request =async <T>(
        method: 'GET' | 'POST',
        url: NitroFetchRequest,
        opts?: UseFetchOptions<ApiResponse<T>>
    ) => {
        const headers = {
            'Content-Type': 'application/json;charset=utf-8',
             'lang':useCookie('lang').value||'en',
             'tenant-id': '1',
            ...opts?.headers
        }

        const { data, pending, refresh } =await useFetch<ApiResponse<T>>(url, {
            baseURL,
            method,
            server: true,
            ...opts,
            headers,
            onResponseError: (err) => {
                console.log('请求错误：', err)
            },
        })
        return { data:data.value?.data, pending:pending.value, refresh }
    }

    return {
        get:async <T>(url: string, params?: object) =>
            request<T>('GET', url, { params }),

        post:async <T>(url: string, body?: object) =>
            request<T>('POST', url, { body }),

        json:async <T>(url: string, body?: object) =>
            request<T>('POST', url, {
                body
            })
    }
}
